package com.wx.mythread.background;


/**
 * 实现死锁
 */
public class MultiThreadError implements Runnable{

    int flag = 1;
    static Object lock1 = new Object();
    static Object lock2 = new Object();

    @Override
    public void run() {
        System.out.println("flag="+flag);
        if (flag == 1){
            synchronized (lock1){
                System.out.println(Thread.currentThread().getName() + "获取到了lock1");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock2){
                    System.out.println(Thread.currentThread().getName() + "获取到了lock2");
                }
            }
        }
        if (flag == 0){
            synchronized (lock2){
                System.out.println(Thread.currentThread().getName() + "获取到了lock1");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock1){
                    System.out.println(Thread.currentThread().getName() + "获取到了lock2");
                }
            }
        }
    }

    public static void main(String[] args) {
        MultiThreadError r1 = new MultiThreadError();
        MultiThreadError r2 = new MultiThreadError();
        r1.flag = 1;
        r2.flag = 0;
        Thread thread1 = new Thread(r1);
        Thread thread2 = new Thread(r2);
        thread1.start();
        thread2.start();
    }
}
